import { LoginUser } from '@/models/LoginUser'
import { b64_decode, b64_encode } from '@/utils/YunMaiUtils'
import type { CaseReducer, PayloadAction } from '@reduxjs/toolkit'
import { createSlice } from '@reduxjs/toolkit'

export const loginUserSlice = createSlice<
  LoginUser,
  {
    updateLoginUser: CaseReducer<
      LoginUser,
      PayloadAction<LoginUser | undefined>
    >
  },
  'loginUser'
>({
  name: 'loginUser',
  initialState: () => {
    const initialState = new LoginUser()
    const loginUserSecret = localStorage.getItem('loginUser')
    if (loginUserSecret) {
      try {
        Object.assign(initialState, JSON.parse(b64_decode(loginUserSecret)))
      } catch (e) {
        console.error('loginUserSlice--loginUser', e)
      }
    }
    return initialState
  },
  reducers: {
    updateLoginUser: (state, { payload = new LoginUser() }) => {
      localStorage.setItem('loginUser', b64_encode(JSON.stringify(payload)))
      return { ...payload }
    }
  }
})
